package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import classes.Artikal;
import classes.VraceniArtikli;

public class VraceniArtikliDAO {
	@SuppressWarnings("unused")
	private final Connection c;
	private final PreparedStatement qSelect, qInsert, qSelectAll, qDelete;
	
	public  VraceniArtikliDAO(Connection c) throws Exception {
		this.c = c;
		
		qInsert= c.prepareStatement("INSERT INTO vraceniartikli(idVraceniArtikli, razlogVracanja, datumVracanja, kolicina, Stavka_idStavka) VALUES(null, ?,?,?,?)");
		qSelect= c.prepareStatement("SELECT razlogVracanja FROM vraceniartikli WHERE  idVraceniArtikli= ?");
		qSelectAll = c.prepareStatement("SELECT * FROM vraceniartikli");
		qDelete = c.prepareStatement("DELETE FROM vraceniartikli WHERE idVraceniArtikli=?");
	}

	public int insertArtikal(VraceniArtikli a) throws Exception {
		if (a==null)
			throw new Exception("Nije moguce dodati nepostojeci artikal!");
        
		qInsert.setString(1, a.getRazlogVracanja());
		qInsert.setDate(2, a.getDatum());
		qInsert.setFloat(3, a.getKolicina());
		qInsert.setInt(4, a.getStavka().getIdStavka());		
		try{
			int rezultat= qInsert.executeUpdate();
			return rezultat;
		}
		catch(Exception ex){
			throw new Exception("Greska kod dodavanja artikla!");
		}
	}
	

	public List<VraceniArtikli> selectSviVraceniArtikli() throws Exception{
		ResultSet rs = qSelectAll.executeQuery();
		List<VraceniArtikli> vraceniartikli = new ArrayList<VraceniArtikli>();
		while (rs.next()){
			VraceniArtikli a= new VraceniArtikli();
			
			a.setIdVraceniArtikli(rs.getInt("id_VraceniArtikli"));
			a.setDatum(rs.getDate("datumVracanja"));
			a.setKolicina(rs.getFloat("kolicina"));
			a.setStavka(DAOFactory.getStavkaDAO().selectStavka(rs.getInt("Stavka_idStavka")));
			vraceniartikli.add(a);
		}
		return vraceniartikli;
	}
	

	public int deleteVraceniArtikal(int id) throws Exception {
		qDelete.setInt(1, id);
		return qDelete.executeUpdate();
	}
}